package Search;

/**
 * @author yyq
 * @create 2021-10-22 14:37
 * 二分查找
 * 前提是有序数组
 */
public class BinarySearch_xt {

    public static int[] binaryFind(int[] a,int val){
        int low=0;
        int high=a.length-1;
        int mid=(low+high)/2;
        while(low<high){
            if(a[mid]==val){
                int[] b=new int[10];
                int i=0;
                b[i]=mid;
                i++;

                int temp=mid+1;
                //向右探测
                while (true)
                {
                    //需要分别往左右两个方向探测
                    if(a[temp]!=val) break;
                    b[i]=temp;
                    temp++;
                    i++;
                }
                temp=mid-1;
                //向左探测
                while (true){
                    //需要分别往左右两个方向探测
                    if(a[temp]!=val) break;
                    b[i]=temp;
                    temp--;
                    i++;
                }
                return b;
            }
            if(a[mid]<val){
                low=mid+1;
                mid=(low+high)/2;
                continue;
            }
            if(a[mid]>val){
                high=mid-1;
                mid=(low+high)/2;
                continue;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[] a={1,8, 10, 89, 1000,1000,1000, 1234};
        int[] ints = binaryFind(a, 1000);
        if(ints==null) System.out.println("没找到");
        else {
            for (int i = 0; i < ints.length; i++) {

                System.out.println("找到了" + ints[i]);
            }
        }
    }
}
